<template>
  <input type="file" id="qqq" accept="image/*" hidden @change="handleFileChange" ref="inputer">
</template>
<script>
export default {
  data() {
    return {
      id: ''
    }
  },
  prop: {    value: {
      // 绑定默认的value prop
      default: undefined
    }  },
  methods: {
    handleFileChange() {
      let inputDOM = this.$refs.inputer
      this.file = inputDOM.files[0]
      this.fileText = '';
      let size = Math.floor(this.file.size / 1024);
      console.log(size);
      if (size > 1024 * 2) {
        // 这里可以加个文件大小控制
        // this.canvasMinify(this.file);
      }
      //上传图片
      this.upLoadImg(this.file);
      //将图片base64传给父容器
      this.fileName = this.file.name;
      this.canvasMinify(this.file);
      this.onChange && this.onChange(this.file, inputDOM.value);
    },
    //canvas压缩图片
    canvasMinify(file) {
      let vm = this;
      console.log(file);
      var reader = new FileReader();
      let base64img = '';
      reader.readAsDataURL(file);
      reader.onload = function (e) {
        var imgObj = new Image();
        imgObj.src = this.result;
        imgObj.onload = function (a) {
          var canvas = document.createElement('canvas');
          canvas.width = imgObj.width;
          canvas.height = imgObj.height;
          var ctx = canvas.getContext("2d");
          ctx.drawImage(imgObj, 0, 0, canvas.width, canvas.height);
          base64img = canvas.toDataURL("image/jpeg", 0.9);
          vm.$emit('fileData', base64img);
        }
      }
    },
    //上传图片
    upLoadImg(data) {

    }
  },
}
</script>
<style lang="less" scoped>
</style>

